<template>
  <n-card :bordered="false" class="mt-4 proCard">
    <BasicForm @register="register" @submit="handleSubmit">
      <template #timeSelect="{ model, field }">
        <n-date-picker
          v-model:formatted-value="model[field]"
          clearable
          type="daterange"
          value-format="yyyy-MM-dd"
        />
      </template>
      <template #ltvDays="{ model, field }">
        <n-input v-model:value="model[field]" clearable placeholder="格式示例：ROI15" />
      </template>
    </BasicForm>
  </n-card>
  <BasicTable
    ref="actionRef"
    :actionColumn="actionColumn"
    :columns="tableCols"
    :request="loadDataTable"
    :row-key="(row) => row.id"
    :scroll-x="2048"
  >
    <template #toolbar>
      <n-button type="primary" @click="reloadTable">刷新数据</n-button>
    </template>
  </BasicTable>

  <basicModal
    ref="modalRef"
    class="basicModal"
    style="width: 30%"
    @register="modalRegister"
    @on-ok="okModal"
  >
    <template #default>
      <BasicForm class="basicForm" @register="editRegister"></BasicForm>
    </template>
  </basicModal>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, unref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { getStatisticsRoiResList, setStatisticsRoiExpand } from '@/api/statistics/daily';
  import { BasicTable, TableAction } from '@/components/Table';
  import { useModal } from '@/components/Modal';
import { forEach } from 'lodash';

  const message = useMessage();

  interface httpReqParms {
    timeFilter: string;
    roiDailyFilter: string;
  }

  interface tableCol {
    key: string;
    title: string;
    width: number;
  }

  interface DataRow {
    [key: string]: string;
  }

  interface tableCol {
    key: string;
    title: string;
    width: number;
  }

  let tableCols = ref<tableCol[]>([]);
  const actionRef = ref();
  let reqParms = ref(<httpReqParms>{
    timeFilter: '',
    roiDailyFilter: '',
  });

  const schemas: FormSchema[] = [
    {
      field: 'ltvDays',
      component: 'NInput',
      label: 'ROI查询：',
      slot: 'ltvDays',
    },
    {
      field: 'timeSelect',
      label: '查询日期：',
      componentProps: {
        placeholder: '日期',
      },
      slot: 'timeSelect',
    },
  ];

  const actionColumn = reactive({
    width: 100,
    title: '操作',
    key: 'action',
    fixed: 'left',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '消耗绑定',
            onClick: handleRoiExpandEdit.bind(null, record),
            type: 'warning',
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  const [modalRegister, { openModal, closeModal, setProps, setSubLoading }] = useModal({
    title: '编辑',
  });

  const okModal = async () => {
    let formValue = await addSubmit();
    if (
      /^-?\d+(\.\d+)?$/.test(formValue.roiExpand) === false ||
      /^\d{4}-\d{2}-\d{2}$/.test(formValue.expandTime) === false
    ) {
      message.warning('格式错误！');
      return;
    }

    try {
      await setStatisticsRoiExpand({
        date: formValue.expandTime,
        expendAmount: formValue.roiExpand,
      });
      message.success('更新成功，页面刷新后配置生效');
      closeModal();
    } finally {
      setSubLoading(false);
    }
  };

  const [editRegister, { submit: addSubmit, setFieldsValue: addSetFieldsValue }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: [
      {
        field: 'expandTime',
        component: 'NInput',
        label: '消耗日期',
        componentProps: {
          placeholder: '消耗日期',
        },
      },
      {
        field: 'roiExpand',
        component: 'NInput',
        label: 'ROI消耗',
        componentProps: {
          placeholder: 'ROI消耗',
        },
      },
    ],
  });

  async function handleRoiExpandEdit(record: Recordable) {
    await openModal();
    setProps({ title: '编辑' });
    let obj = Object.assign({}, unref(record), {
      roiExpand: unref(record).expendAmount + '',
      expandTime: unref(record).date,
    });
    await addSetFieldsValue(obj);
  }

  const [register] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 100,
    schemas: schemas,
  });

  const handleSubmit = (values: Recordable) => {
    if (values.ltvDays && !/^ROI\d+/.test(values.ltvDays)) {
      message.warning('格式错误！');
      return;
    }
    reqParms.value.timeFilter = values.timeSelect
      ? values.timeSelect[0] + ':' + values.timeSelect[1]
      : '';
    reqParms.value.roiDailyFilter = values.ltvDays ? values.ltvDays : '';
    genTableColKeyHandle();
    reloadTable();
  };

  //table 列
  const genTableColKeyHandle = () => {
    tableCols.value = [];
    tableCols.value.push(<tableCol>{
      key: 'date',
      title: '注册日期',
      width: 97,
    });
    tableCols.value.push(<tableCol>{
      key: 'expendAmount',
      title: '消耗',
      width: 100,
    });
    let colRange =
      reqParms.value.roiDailyFilter === ''
        ? 90
        : Number(reqParms.value.roiDailyFilter.substring(3));
    for (let i = 1; i <= colRange; ) {
      let lcsKey = i <= 90 ? i : (Math.floor(i / 30) + 1) * 30;
      let title = 'ROI' + lcsKey;
      tableCols.value.push(<tableCol>{
        key: 'ROI' + lcsKey,
        title: title,
        width: 75,
      });

      if (i <= 90) {
        i++;
      } else {
        i += 30;
      }
    }
  };

  onMounted(() => {
    genTableColKeyHandle();
  });

  const loadDataTable = async () => {
    let data = await getStatisticsRoiResList(unref(reqParms));
    let rows: DataRow[] = [];
    for (const [date, values] of Object.entries(data)) {
      if (typeof values === 'object' && values !== null) {
        let row: DataRow = {};
        row['date'] = date as string;
        for (const key in values) {
          if (key === 'expendAmount') {
            row['expendAmount'] = String(values[key]);
          } else {
            row[key] = values[key] as string;
          }
        }
        rows.push(row);
      }
    }
    rows.sort((a, b) => {
      return new Date(b.date).getTime() - new Date(a.date).getTime();
    });
    rows.forEach(element => {
      for (let i = 1; i <= 90; i++ ) {
        let pre_i = i-1;
        let pre_item = element['ROI' + pre_i];
        let title = 'ROI' + i;
        let item = element[title];
        if(!item)
        {
          element[title] = '0';
          if(pre_item)
          {
            element[title] = pre_item;
          }
        }
      }
    });
    return { list: rows, total: rows.length, pageSize: 10, page: 1 };
  };

  const reloadTable = () => {
    actionRef.value.reload();
  };
</script>

<style lang="less" scoped></style>
